import multer from '@koa/multer'
import { Context, Next } from 'koa'

// 定义文件类型接口
interface UploadedFile {
  fieldname: string
  originalname: string
  encoding: string
  mimetype: string
  buffer: Buffer
  size: number
}

// 文件过滤器
const fileFilter = (req: any, file: UploadedFile, cb: (error: Error | null, acceptFile: boolean) => void) => {
  // 允许的文件类型
  const allowedMimeTypes = [
    'image/jpeg',
    'image/jpg', 
    'image/png',
    'image/gif',
    'image/webp'
  ]

  if (allowedMimeTypes.includes(file.mimetype)) {
    cb(null, true)
  } else {
    cb(new Error('只支持 JPEG、PNG、GIF、WebP 格式的图片文件'), false)
  }
}

// 配置multer
const upload = multer({
  storage: multer.memoryStorage(), // 使用内存存储，不保存到本地
  limits: {
    fileSize: 2 * 1024 * 1024, // 限制文件大小为2MB
    files: 1 // 只允许上传一个文件
  },
  fileFilter: fileFilter
})

// 头像上传中间件
export const avatarUpload = upload.single('avatar')

// 错误处理中间件
export const uploadErrorHandler = async (ctx: Context, next: Next) => {
  try {
    await next()
  } catch (error: any) {
    // 检查是否为multer错误
    if (error.code) {
      switch (error.code) {
        case 'LIMIT_FILE_SIZE':
          ctx.status = 400
          ctx.body = {
            success: false,
            message: '文件大小不能超过2MB'
          }
          break
        case 'LIMIT_FILE_COUNT':
          ctx.status = 400
          ctx.body = {
            success: false,
            message: '只能上传一个文件'
          }
          break
        case 'LIMIT_UNEXPECTED_FILE':
          ctx.status = 400
          ctx.body = {
            success: false,
            message: '上传的文件字段名不正确'
          }
          break
        default:
          ctx.status = 400
          ctx.body = {
            success: false,
            message: '文件上传失败'
          }
      }
    } else {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: error.message || '文件上传失败'
      }
    }
  }
}

// 文件验证中间件
export const validateFile = async (ctx: Context, next: Next) => {
  const file = (ctx as any).file as UploadedFile

  if (!file) {
    ctx.status = 400
    ctx.body = {
      success: false,
      message: '请选择要上传的文件'
    }
    return
  }

  // 验证文件大小
  if (file.size > 2 * 1024 * 1024) {
    ctx.status = 400
    ctx.body = {
      success: false,
      message: '文件大小不能超过2MB'
    }
    return
  }

  // 验证文件类型
  const allowedMimeTypes = [
    'image/jpeg',
    'image/jpg',
    'image/png', 
    'image/gif',
    'image/webp'
  ]

  if (!allowedMimeTypes.includes(file.mimetype)) {
    ctx.status = 400
    ctx.body = {
      success: false,
      message: '只支持 JPEG、PNG、GIF、WebP 格式的图片文件'
    }
    return
  }

  await next()
} 